<?php

namespace app\system\service;

use app\common\Jwt;
use app\model\SystemMenu;
use app\model\SystemUser;
use app\model\User;
use app\traits\ServiceTrait;
use think\facade\Request;
use think\helper\Arr;

class WechatUserService
{
    use ServiceTrait;

    public function getList(?array $params = null, $field = ['*'])
    {
        $query = User::order(['id' => 'desc']);
        if ($username = Arr::get($params, 'username')) {
            $query->where(['username' => $username]);
        }
        if ($nickname = Arr::get($params, 'nickname')) {
            $query->where('nickname', 'like', "%$nickname%");
        }
        if ($phone = Arr::get($params, 'phone')) {
            $query->where(['phone' => $phone]);
        }
        if ($loginTime = Arr::get($params, 'login_time')) {
            $query->whereBetween('login_time', $loginTime);
        }
        if ($createdAt = Arr::get($params, 'created_at')) {
            $query->whereBetween('created_at', $createdAt);
        }
        $pagination = $query->with('avatar_upload')
            ->field($field)
            ->paginate([
                'list_rows' => Arr::get($params, $this->listRowsName('system'), 15),
                'var_page' => 'page',
            ]);
        return pagination($pagination);
    }

    public function update($id, $data)
    {
        if (!$model = User::where(['id' => $id])->find()) {
            return [false, '资源不存在'];
        }
        return User::update($data, ['id' => $model->id]);
    }

    public function updateFieldStatus($id, ?array $data = null)
    {
        if (!$model = User::where(['id' => $id])->find()) {
            return [false, '资源不存在'];
        }
        $fieldName = Arr::get($data, 'field');
        if ($fieldName == 'nickname_status') {
            $data['nickname_status'] = $model->nickname_status == 1 ? 2 : 1;
        }
        if ($fieldName == 'avatar_id_status') {
            $data['avatar_id_status'] = $model->avatar_id_status     == 1 ? 2 : 1;
        }
        return User::update($data, ['id' => $id]);
    }
}